package org.duang.logs.db.elasticsearch;

import java.net.InetAddress;
import java.util.List;

import org.duang.db.elasticsearch.ESearch;
import org.duang.logs.db.ILogDBFactory;
import org.duang.logs.db.ToolUtils;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;

public class ElasticSearchLogBackDBFactory implements ILogDBFactory<XContentBuilder> {

	private static ElasticSearchLogBackDBFactory dbFactory;
	private static ESearch search;
	private static IndexRequestBuilder indexRequestBuilder;

	public static ElasticSearchLogBackDBFactory init() {
		if (null == dbFactory) {
			dbFactory = new ElasticSearchLogBackDBFactory();
		}
		return dbFactory;
	}

	public ElasticSearchLogBackDBFactory() {
		if (search == null) {
			try {
				indexRequestBuilder = getElasticSearchDB();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			indexRequestBuilder = search.getDB(ToolUtils.getIndexName(), ToolUtils.getTypeName());
		}
	}

	private static IndexRequestBuilder getElasticSearchDB() throws Exception {
		List<String> list = ToolUtils.getEsHost();
		TransportAddress address = new InetSocketTransportAddress(InetAddress.getByName(list.get(0)), ToolUtils.getEsPort());
		Client client = TransportClient.builder().build().addTransportAddress(address);
//		System.out.println("########logback for elasticsearch:  " +  address.getHost() + ":"+ address.getPort() +",  index: " + ToolUtils.getIndexName() +",  type: " + ToolUtils.getTypeName());
		indexRequestBuilder = client.prepareIndex(ToolUtils.getIndexName(), ToolUtils.getTypeName()).setRefresh(true);
		return indexRequestBuilder;
	}

	@Override
	public boolean insert(XContentBuilder builder) {
		try {
			IndexResponse response = indexRequestBuilder.setSource(builder.endObject().string()).execute().actionGet();
			if (response.getId().length() == 20) {
				return true;
			} else {
				throw new RuntimeException("insert data to elasticsearch fail!!!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}	
}
